from flask import Flask, jsonify
from flask_cors import CORS
import pymysql

app = Flask(__name__)
CORS(app)

# 数据库配置
db_config = {
    'host': 'localhost',
    'user': 'root',
    'password': '123456',
    'database': 'gridvision',
    'charset': 'utf8',
    'cursorclass': pymysql.cursors.DictCursor
}

@app.route('/api/inspection-data', methods=['GET'])
def get_inspection_data():
    try:
        # 连接数据库
        connection = pymysql.connect(**db_config)
        cursor = connection.cursor(pymysql.cursors.DictCursor)

        # 查询所有区域的名称和检测次数
        cursor.execute("SELECT area_name, history_defects FROM inspection_areas")
        results = cursor.fetchall()

        if not results:
            return jsonify({"message": "No data found"}), 404

        # 按照检测次数排序，并截取前5个
        top_areas = sorted(results, key=lambda x: x['history_defects'], reverse=True)[:5]

        # 重新计算总数（只计算前5个的总数用于饼状图百分比）
        total_defects = sum(row['history_defects'] for row in top_areas)

        # 构造饼图数据
        pie_data = [
            {"name": row["area_name"], "value": row["history_defects"]}
            for row in top_areas
        ]

        # 构造列表数据（可直接复用 pie_data）
        top_list = [
            {"area_name": row["area_name"], "defect_count": row["history_defects"]}
            for row in top_areas
        ]

        return jsonify({
            "total_defects": total_defects,
            "pie_data": pie_data,
            "top_areas": top_list
        })

    except Exception as e:
        import traceback
        traceback.print_exc()
        return jsonify({"error": str(e)}), 500

    finally:
        cursor.close()
        connection.close()



if __name__ == '__main__':
    app.run(debug=True, port=5000)